import '../assets/css/Layout.css';
import { Link, Outlet, useNavigate } from 'react-router-dom';
import { useSelector } from 'react-redux';
import moment from 'moment';
import type { MenuProps } from 'antd';
import { Dropdown, Menu } from 'antd';
import router from '../router/router';
import { Breadcrumb } from 'antd';
import { useEffect, useState } from 'react';

export default function Child() {
    const user = useSelector(state => state.userSlice.user);
    const time = user ? moment(user.ctime).format("YYYY年M月D日 HH:mm:ss") : '';
    const navigate = useNavigate();
    const [breadcrumbItems, setBreadcrumbItems] = useState([{ title: '系统', href: '/' }]);

    // 检查登录状态
    useEffect(() => {
        if (!user.id) {
            // 如果用户未登录，强制跳转到登录页
            navigate('/login');
        }
    }, [user, navigate]);

    // 定义路径合并函数
    function mergePaths(parentpath, childPath) {
        if (!childPath || parentpath === childPath) {
            return parentpath;
        }
        return `${parentpath}/${childPath}`.replace(/\/+/g, '/');
    }

    const menuData = router.routes[0].children
        .filter((item) => {
            if (item.meta?.role) {
                return item.meta.role.includes(user?.purview);
            }
            return true;
        })
        .map((item, index) => ({
            key: `${item.path}-${index}`, // 添加唯一标识符
            path: item.path, // 保存真实路径
            label: item.title,
            icon: item.icon,
            children: item.children
                ? item.children.map((subItem, subIndex) => ({
                    key: `${mergePaths(item.path, subItem.path)}-${index}-${subIndex}`, // 子菜单唯一标识
                    path: mergePaths(item.path, subItem.path), // 子菜单真实路径
                    label: subItem.title,
                    parenttitle: item.title,
                    parentpath: item.path,
                }))
                : null,
        }));

    const onClick: MenuProps['onClick'] = (e) => {
        const foundItem = menuData.find((item) => {
            if (item.children) {
                return item.children.some((subItem) => subItem.key === e.key);
            }
            return item.key === e.key;
        });

        if (foundItem) {
            if (foundItem.children) {
                const foundSubItem = foundItem.children.find((subItem) => subItem.key === e.key);
                if (foundSubItem) {
                    navigate(foundSubItem.path);
                    setBreadcrumbItems([
                        { title: '系统', href: '/' },
                        { title: foundSubItem.parenttitle, href: foundSubItem.parentpath },
                        { title: foundSubItem.label, href: foundSubItem.path },
                    ]);
                    return;
                }
            }

            navigate(foundItem.path);
            setBreadcrumbItems([
                { title: '系统', href: '/' },
                { title: foundItem.label, href: foundItem.path },
            ]);
        } else {
            navigate('/');
        }
    };

    function itemRender(currentRoute, params, items, paths) {
        const isLast = currentRoute?.href === items[items.length - 1]?.href;

        return isLast ? (
            <Link style={{ color: '#000' }} to={currentRoute.href}>{currentRoute.title}</Link> // 其他面包屑使用 Link 跳转
        ) : (
            <Link to={currentRoute.href}>{currentRoute.title}</Link> // 其他面包屑使用 Link 跳转
        );
    }

    const items = [
        {
            key: '1',
            label: (
                <a href='' onClick={() => localStorage.clear()}>退出登录</a>
            ),
        },
        {
            key: '2',
            label: (
                <a href='/echarts'>查看图表</a>
            ),
        },
    ]


    return (
        <div className="body" style={{ width: '100%', height: '100vh', overflow: 'hidden' }}>
            <header className="header">
                <div className="header_left"></div>
                <div className="header_right">
                    {user && (
                        <>
                            <p>{time}</p>
                            <Dropdown menu={{ items }} placement="bottom" arrow>
                                <img className="account_img" src={user.head} alt="" />
                            </Dropdown>
                            <div className="userInfo">
                                <p>{user.name}</p>
                                <p>{user.purview}</p>
                            </div>
                        </>
                    )}
                </div>
            </header>
            <main className="content">
                <aside className="aside">
                    <Menu
                        onClick={onClick}
                        style={{
                            width: 200,
                            color: 'white',
                        }}
                        defaultSelectedKeys={['/']}
                        defaultOpenKeys={['/']}
                        mode="inline"
                        items={menuData}
                        theme="primary"
                    />
                </aside>
                <div className="main_content">
                    <div className="tabBar">
                        <Breadcrumb
                            itemRender={itemRender}
                            items={breadcrumbItems}
                            separator=">"
                        />
                    </div>
                    <div className="outlet">
                        <Outlet />
                    </div>
                </div>
            </main>
        </div>
    );
}
